﻿using System;
using System.Linq;
using System.Web.Http;
using ScrambledEggs.Entities;

namespace ScrambledEggs.Controllers.Api
{
    public class NotificationsController : ApiController
    {
        private readonly ScrambledEggsEntities _entities;

        public NotificationsController()
        {
            // ReSharper disable EmptyGeneralCatchClause
            try
            {
                var conn = System.Configuration.ConfigurationManager.ConnectionStrings["ScrambledEggsConnection"].ConnectionString;
                _entities = new ScrambledEggsEntities(conn);
            }
            catch (Exception)
            {

            }
            // ReSharper restore EmptyGeneralCatchClause
        }

        public void Put(NotificationModel model)
        {
            var save = _entities.Saves.SingleOrDefault(s => s.StateKey == model.SaveKey)
                ?? _entities.Saves.Add(new Save { StateKey = model.SaveKey });

            if (save.StateKey == default(Guid))
                save.StateKey = Guid.NewGuid();

            save.Email = model.Email; // could override existing, but that's okay :)
            save.LastUpdate = DateTime.Now;
            _entities.SaveChanges();
        }

        public class NotificationModel
        {
            public Guid SaveKey { get; set; }
            public String Email { get; set; }
        }
    }
}